import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int top = 0;
        int left = 0;
        int buttom = matrix.length - 1;
        int right = matrix[0].length - 1;
        List<Integer> res = new ArrayList<>();
        while (left <= right && top <= buttom) {
            //向右
            for (int i = left; i <= right; i++) {
                res.add(matrix[top][i]);
            }
            top++;
            //右下
            for (int i = top; i <= buttom; i++) {
                res.add(matrix[i][right]);
            }
            right--;
            //向左
            if (top <= buttom) {
                for (int i = right; i >= left; i--) {
                    res.add(matrix[buttom][i]);
                }
                buttom--;
            }

            //向上
            if (left <= right) {
                for (int i = buttom; i >= top; i--) {
                    res.add(matrix[i][left]);
                }
                left++;

            }

        }
        return res;
    }
}